<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta
            name="viewport"
            content="initial-scale=1.0, user-scalable=no, width=device-width"
    />
    <title>HELLO，AMAP!</title>

    <script type="text/javascript">
        window._AMapSecurityConfig = {
          securityJsCode: "efdd63c8b81c4a47b4c052be83e4dbc7",
        };
    </script>
    <script src="https://webapi.amap.com/loader.js"></script>
    <script type="text/javascript">
        var map
        var AMapObj

         AMapLoader.load({
           key: "ac71a4daf52d8d8254b6144c92dfae8c", //申请好的Web端开发者 Key，调用 load 时必填
           version: "2.0", //指定要加载的 JS API 的版本，缺省时默认为 1.4.15
         })
           .then((AMap) => {
             AMapObj=AMap
              map = new AMap.Map("container");
           })
           .catch((e) => {
             console.error(e); //加载错误提示
           });
    </script>
    <style>
        html,
        body,
        #container {
          width: 100%;
          height: 100%;
        }
    </style>

</head>
<script>

    // window.onmessage = (event)=>{

    // }
    var port
    window.addEventListener("message",(event)=>{
         if(event.data === "mess_port") {
            port=event.ports[0]//拿到端口
            onNativeMessage()
            sendMessage({type:'alert',value:'老高牛比!!!'})

         }
    })

    function sendMessage(obj){
          if(obj){
            if(typeof obj !== "string"){
              port.postMessage(JSON.stringify(obj))
            }else{
              port.postMessage(obj)
            }

          }


    }

    function onNativeMessage(){
      if(port){
           port.onmessage = (event)=>{
             // alert(event.data)
             let res=event.data
             if(typeof res ==='string'){
                    res=JSON.parse(res)
             }
              map.setCenter([res.longitude,res.latitude]);
              map.setZoom(15)

              addMarker(res.longitude,res.latitude)

           }

          }

    }


     // 实例化点标记
function addMarker(longitude,latitude) {
  if (!marker) {
    marker = new AMapObj.Marker({
      icon: "//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png",
      position: [longitude, latitude],
      offset: new AMapObj.Pixel(-13, -30)
    });
    marker.setMap(map);
  }

}


</script>
<body>
<div id="container"></div>
</body>
</html>